package com.lwx.http.httpclient;

import java.io.IOException;
import java.net.URI;
import java.util.List;

import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;

public class HttpClientMain {
    public static void main(String[] args) {
        System.err.println(getLocationUrl2("http://product.mobogenie.com/android/clientDownload.htm?media=1036&product_id=10&apkid=com.cleanmaster.mguard&t=1"));
    }
    
    public static String getLocationUrl(String oriUrl){
        String locationUrl = "";
        
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpClientContext context = HttpClientContext.create();
        HttpGet httpget = new HttpGet(oriUrl);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget, context);
            HttpHost target = context.getTargetHost();
            List<URI> redirectLocations = context.getRedirectLocations();
            URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
            locationUrl = location.toASCIIString();
            // Expected to be an absolute URI
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return locationUrl;
    }
    
    public static String getLocationUrl2(String oriUrl){
        String locationUrl = "";
        
        LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
        CloseableHttpClient httpclient = HttpClients.custom()
                .setRedirectStrategy(redirectStrategy)
                .disableRedirectHandling()
                .build();
        HttpClientContext context = HttpClientContext.create();
        HttpGet httpget = new HttpGet(oriUrl);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget, context);
            locationUrl = redirectStrategy.getLocationURI(httpget, response, context).toASCIIString();
            // Expected to be an absolute URI
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return locationUrl;
    }
}
